package top.auntie.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.sqlite.date.DateFormatUtils;
import top.auntie.bean.PageReq;
import top.auntie.common.Constants;
import top.auntie.dao.OrgTypeDao;
import top.auntie.dao.TypeDao;
import top.auntie.model.OrgTypeExample;
import top.auntie.model.Type;
import top.auntie.model.TypeExample;
import top.auntie.service.TypeService;
import top.auntie.util.DateTimeUtils;

import javax.lang.model.element.TypeElement;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeDao typeDao;

    @Autowired
    private OrgTypeDao orgTypeDao;

    @Override
    public PageInfo<Type> queryType(PageReq pageReq) {
        TypeExample example = new TypeExample();
        example.createCriteria().andDeletedAtIsNull();
        PageHelper.startPage(pageReq.getPage(), pageReq.getLimit());
        return new PageInfo<>(typeDao.selectByExample(example));
    }

    @Override
    public void saveType(Type type) {
        if (type.getId()!=null) {
            type.setUpdatedAt(DateTimeUtils.getNowDateTimeStr());
            typeDao.updateByPrimaryKeySelective(type);
        } else {
            type.setCreatedAt(DateTimeUtils.getNowDateTimeStr());
            typeDao.insertSelective(type);
        }
    }

    @Override
    public void deleteType(Integer id) throws Exception {
//        Type record = new Type();
//        record.setId(id);
//        record.setDeletedAt(DateFormatUtils.format(new Date(), Constants.TIME_PATTERN));
//        typeDao.updateByPrimaryKeySelective(record);
        OrgTypeExample example = new OrgTypeExample();
        example.createCriteria().andTypeIdEqualTo(id);
        if (!orgTypeDao.selectByExample(example).isEmpty()) {
            throw new Exception("当前项目类型正在使用中，无法删除");
        }
        typeDao.deleteByPrimaryKey(id);
    }

    @Override
    public Type getTypeById(Integer id) {
        return typeDao.selectByPrimaryKey(id);
    }

    @Override
    public List<Type> getTypesByOrgId(Integer orgId) {
        return typeDao.findTypesByOrgId(orgId);
    }

    @Override
    public List<Type> getAllTypes() {
        return typeDao.selectByExample(new TypeExample());
    }

}
